<template>
  <div class="containers">
    <el-button type="primary" plain size="small" @click="zomViewport(true)">
      <el-icon>
        <ZoomIn />
      </el-icon>放大</el-button>
    <el-button type="primary" plain size="small" @click="zomViewport(false)">
      <el-icon>
        <ZoomOut />
      </el-icon>缩小</el-button>
    <el-button type="info" plain size="small" @click="fitViewport"><el-icon>
        <Rank />
      </el-icon>自适应</el-button>
    <div class="canvas" ref="canvasRef"></div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import BpmnViewer from 'bpmn-js/lib/Viewer'
const props = defineProps({
  flowData: Object,
  // processInstance: Object,
})
const canvasRef = ref()
const bpmnViewer = ref()
function init() {
  // console.log('执行init')
  bpmnViewer.value = new BpmnViewer({
    container: canvasRef.value,
    height: 'calc(100vh - 500px)',
    keyboard: {
      bindTo: window
    }
  })
  // console.log('flowDataInit:', props.value.flowData)
  // loadFlowCanvas()
  // fitViewport()
}
async function loadFlowCanvas(xml) {
  try {
    // console.log('flowData:', xml)
    await bpmnViewer.value.importXML(xml)
  } catch (e) {
    console.log(e.message, e.warnings)
  }
}
async function fitViewport() {
  // console.log('居中')
  await bpmnViewer.value.get('canvas').zoom("fit-viewport", "auto")
}

async function setColor() {
  const canvas = bpmnViewer.value.get('canvas')
  const allShapes = await bpmnViewer.value.get("elementRegistry").getAll()
  allShapes.forEach(element => {
    // console.log(element)
    const shapeId = element.businessObject.id

    // console.log('shapeAttrs', shapeAttrs)
    props.flowData.nodeData?.forEach(node => {
      if (node.key === shapeId && node.completed) {
        // console.log(shapeId)
        canvas.addMarker(shapeId, "highlight")
      }
    })
  });
}

watch(props,
  async (newValue) => {
    // console.log('执行watch', newValue, oldValue)
    if (newValue.flowData) {
      bpmnViewer.value && bpmnViewer.value.destroy()
      init()
    }

    await loadFlowCanvas(newValue.flowData.xmlData)
    setColor()
    fitViewport()

  },
  { deep: true, immediate: true },
)

function zomViewport(zoomIn = true) {
  let zoom = bpmnViewer.value.get('canvas').zoom()
  zoom += (zoomIn ? 0.1 : -0.1)
  if (zoom > 0.2) bpmnViewer.value.get('canvas').zoom(zoom)
}
</script>

<style lang="less" scoped>
.containers {
  height: 100%;
  width: 100%;
  margin-top: 20px;


  .el-icon {
    margin-right: 8px;
  }
}

:deep(.highlight) {
  .djs-visual {

    circle,
    rect:first-child {
      stroke: rgb(40, 141, 53) !important;
      fill: #d7f6ce !important;
    }
  }
}
</style>